import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { getHomeInfo, getRecommend, getGoods } from "@/service/home";

export interface IGetGoodsPayload {
  type: number;
  page: number;
}

export const getHomeInfoAction = createAsyncThunk("home/info", async () => {
  const res = await getHomeInfo();
  return res.data;
});

export const getRecommendAction = createAsyncThunk(
  "home/recommend",
  async () => {
    const res = await getRecommend();
    return res.data;
  }
);

export const getGoodsAction = createAsyncThunk(
  "home/goods",
  async (payload: IGetGoodsPayload) => {
    const { type, page } = payload;
    const res = await getGoods(type, page);

    return {
      goods: res.data.goods,
      page,
      type,
    };
  }
);

export const tabs = ["specific", "single"]; // 0 1

function getDefaultGoodsList() {
  // goodsList: {
  //   "specific": { // 精选专场
  //     page: 0,
  //     list: []
  //   },
  //   "single": {  // 精选单品
  //     page: 0,
  //     list: []
  //   }
  // }
  const goodsListOrigin = {};
  tabs.forEach((tab) => {
    // { "精选专场": { page:0, list:[] } }
    goodsListOrigin[tab] = { page: 0, list: [] };
  });
  return goodsListOrigin;
}

export interface IHomeState {
  banners: any[];
  populars: any[];
  recommend: any;
  currentTab: string;
  goodsList: any;
}

const initialState: IHomeState = {
  banners: [],
  populars: [],
  recommend: null, // 这个默认值为null，使用时需要判断
  currentTab: tabs[0], // specific  single
  goodsList: getDefaultGoodsList(),
};

const homeSlice = createSlice({
  name: "home",
  initialState,
  reducers: {
    setCurrentTab(state, { payload }) {
      state.currentTab = payload;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getHomeInfoAction.fulfilled, (state, { payload }) => {
        state.banners = payload.adsInfo.slide_ads.config.slide || [];
      })

      .addCase(getRecommendAction.fulfilled, (state, { payload }) => {
        state.populars = payload.populars || [];
        state.recommend = payload.recommend || null;
      })

      .addCase(getGoodsAction.fulfilled, (state, { payload }) => {
        if (payload.goods && payload.goods.length) {
          const { type, page, goods } = payload;
          // 直接修改 page 和 list
          state.goodsList[tabs[type]].list = [
            ...state.goodsList[tabs[type]].list,
            ...goods,
          ];
          state.goodsList[tabs[type]].page = page;
        }
      });
  },
});

// 同步的action
export const { setCurrentTab } = homeSlice.actions;
export default homeSlice.reducer;
